package databases

import (
	"github.com/beego/beego/v2/client/cache"
	"github.com/beego/beego/v2/client/orm"
	"github.com/beego/beego/v2/core/logs"
	"house/models"

	_ "github.com/beego/beego/v2/client/cache/redis"
	_ "github.com/go-sql-driver/mysql"
)

var RedisCLi cache.Cache

func createTable() {
	orm.RegisterModel(new(models.User))
}

func init() {
	initMysql()
	initRedis()
}

func initRedis() {
	var err error
	RedisCLi, err = cache.NewCache("redis", `{"key":"collectionName","conn":":6379","dbNum":"0"}`)
	if err != nil {
		logs.Error("Redis连接失败", err)
		return
	}
}

func initMysql() {
	createTable()
	err := orm.RegisterDriver("mysql", orm.DRMySQL)
	if err != nil {
		logs.Error("数据库连接失败", err)
		return
	}
	err = orm.RegisterDataBase("default", "mysql", "root:@tcp(127.0.0.1:3306)/house")
	if err != nil {
		logs.Error("数据库连接失败", err)
	} else {
		logs.Info("数据库连接成功")
	}
	orm.Debug = true
	err = orm.RunSyncdb("default", false, true)
	if err != nil {
		logs.Error("数据库连接失败", err)
		return
	}
}
